package com.qf.app.approute.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.qf.app.approute.service.AppRouteService;
import com.qf.util.aes.AES;
import com.qf.util.common.JackJson;
import com.qiniu.util.Auth;




/**
*
* 项目名称：qf
* 类名称：AppRouteController
* 类描述：路由表
* 创建人：郭桦
* 创建时间：2015年5月20日  
* @version
*
*/
@SuppressWarnings("all")
@Controller
@RequestMapping("/appRoute")
public class AppRouteController {

	private AppRouteService appuserService;

	public AppRouteService getAppuserService() {
		return appuserService;
	}
	@Autowired
	public void setAppuserService(AppRouteService appuserService) {
		this.appuserService = appuserService;
	}

	private static final String[] controllerArr = { "/timer/queryTimer",
			                                        "/timer/yuyue",
			                                        "/timer/queryPeilian",
			                                        "/timer/getUser",
			                                        "/timer/getTimer",
			                                        "/timer/checkUser",
			                                        "/timer/login",
			                                        "/timer/getPhoto",
			                                        "/timer/addPhoto",
			                                        "/timer/PlPhoto",
			                                        "/timer/resetpassword",
			                                        "/timer/updateUser",
			                                        "/timer/updateHead",
			                                        "/timer/video",
			                                        "/timer/getUserTimer",
			                                        "/timer/getPeilian",
			                                        "/timer/banner",
			                                        "/timer/delPhoto"
			                                        
												};

	
	//判断路径是否有效
	public static boolean useLoop( String targetValue) {
	    for (String s : controllerArr) {
	        if (s.equals(targetValue)) {
	            return true;
	        }
	    }
	    return false;
	}
	
	/**
	 * 处理所有请求
	 * @param para
	 * @param request
	 * @param response
	 * @param file
	 * @return
	 */
	@RequestMapping("route")
	public String toRoute(String para,HttpServletRequest request, HttpServletResponse response,@RequestParam(value="file",required=false)CommonsMultipartFile file){
		Map<String,Object> rm = new HashMap<String,Object>();  //返回信息map
		String returnString = "forward:/appRoute/sendError";
		try{
			System.out.println("ip:"+request.getRemoteAddr());
			System.out.println("para解密前=="+para);
			if(para!=null && !"".equals(para)){
				para = AES.decrypt(para);
				System.out.println("para解密后=="+para);
				Map<String,Object> valueMap = JackJson.fromJsonToObject(para,Map.class);  //传值map
				//判断valueMap是否为空   空返回错误信息
				if(valueMap==null){
					rm.put("result","0");
					rm.put("msg", "para解析成map失败"); 
				}else{
					System.out.println("valuemap===>"+valueMap);
					String action  = (String)valueMap.get("action");
					System.out.println("action==>"+action);
					//分割action
					if(action==null || "".equals(action)){
						rm.put("result","0");
						rm.put("msg", "访问action为空，请填写action信息"); //para为空  信息传递失败
					}else{
						if(useLoop(action)){
							request.setAttribute("valueMap", valueMap);//把解析好的map传递给下一个方法
							request.setAttribute("para", para);
							returnString = "forward:/" + action;
						}else{
							rm.put("result","0");
							rm.put("msg", "访问action无效，请检查action"); 
						}
					}
				}
			}
			request.setAttribute("rm", rm);
		}catch(Exception e){
			e.printStackTrace();
		}
		return returnString;
		
	}
	
	
	private static String ACCESS_KEY = "LD5uBW1UGlUUk5fyYgv0v7aDcNswYZHGc3LWYcsJ";
	private static String SECRET_KEY = "K5NyrqmXbVUTHQkvQKddDSE9zA1inNngjUarxxsE";
	
	@RequestMapping("getToken")
	public void getToken(String para,HttpServletRequest request, HttpServletResponse responsee){
		Map<String,Object> rm = new HashMap<String,Object>();  //返回信息map
		try{
			if(para!=null && !"".equals(para)){
				para = AES.decrypt(para);
				System.out.println("para解密后=="+para);
				Map<String,Object> valueMap = JackJson.fromJsonToObject(para,Map.class);  //传值map
				//判断valueMap是否为空   空返回错误信息
				if(valueMap==null){
					rm.put("result","0");
					rm.put("msg", "para解析成map失败"); 
				}else{
					String bucket  = (String)valueMap.get("bucket");
					System.out.println("bucket==>"+bucket);
					if(bucket==null || "".equals(bucket)){
						rm.put("result","0");
						rm.put("msg", "bucket不能为空"); 
					}else{
						Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
						rm.put("result","1");
						rm.put("token", auth.uploadToken(bucket)); 
					}
				}
			}
			request.setAttribute("rm", rm);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 处理所有请求   后台测试用！！！！！！！！
	 * @param para
	 * @param request
	 * @param response
	 * @param file
	 * @return
	 */
	@RequestMapping("routeTest")
	public String toRouteTest(String para,HttpServletRequest request, HttpServletResponse response,@RequestParam(value="file",required=false)CommonsMultipartFile file){
		Map<String,Object> rm = new HashMap<String,Object>();  //返回信息map
		String returnString = "forward:/appRoute/sendError";
		try{
			para = "uI5wLSfKPe63b2RvoLz4nSstm5IAGwyWmJRKe3RxenzClFSiw0SJ7eZPy/AIzzgaCviD3l4XUgNzR6osEqGXrRS9lK/NeI+Wae4Dw7vFx+VsySEMp0L0NOJYeRh427jBDpYcZTS9BKPI1S5uRL47MHCqllxyOXbwRfw6P7YRywmYC5DkcNbIlS6pRn/LchX6CoyOrdl+XwX9ocGZDcdsGWv3jZNgx7x9sTHFL20jg6JI9R0yf3ZKF9JMzt7j1+EJ78tq1OStE3V/DCRBXGQcbL49/VZNVCarK4aFYERPOQ3KSxECO98cH+suU3sG2k8hJZhD/LsMmR4Ugn4Om4OjxaEP4b/T8I02H6bIlnofBoET8IAYY7upu7BtmfxRGsV0mDhYIu0SvsZTByFIsPWbUAxZoUXoyX1kyikcDPv+WE0+j9mmn+WMbstKglSQfENd"; 
			System.out.println("para解密前=="+para);
			if(para!=null && !"".equals(para)){
				para = AES.decrypt(para);
				System.out.println("para解密后=="+para);
				Map<String,String> valueMap = JackJson.fromJsonToObject(para,Map.class);  //传值map
				//判断valueMap是否为空   空返回错误信息
				if(valueMap==null){
					rm.put("result","0");
					rm.put("msg", "para解析成map失败"); 
				}else{
					System.out.println("valuemap===>"+valueMap);
					String action  = valueMap.get("action");
					System.out.println("action==>"+action);
					//分割action
					if(action==null || "".equals(action)){
						rm.put("result","0");
						rm.put("msg", "访问action为空，请填写action信息"); //para为空  信息传递失败
					}else{
						if(true){
							request.setAttribute("valueMap", valueMap);//把解析好的map传递给下一个方法
							request.setAttribute("para", para);
							returnString = "forward:/" + action ;
						}else{
							rm.put("result","0");
							rm.put("msg", "访问action无效，请检查action"); 
						}
					}
				}
			}
			request.setAttribute("rm", rm);
		}catch(Exception e){
			e.printStackTrace();
		}
		return returnString;
	}
	
	/**
	 * 返回错误信息
	 * @param para
	 * @param request
	 * @param response
	 */
	@RequestMapping("sendError")
	public void sendError(String para,HttpServletRequest request, HttpServletResponse response){
		Map<String,Object> rm = (Map<String,Object>)request.getAttribute("rm");  //返回信息map
		String json  = "";
		try{
			json = JackJson.fromObjectToJson(rm);
			System.out.println("json=="+json);
			String resultjson = AES.encrypt(json);
			response.setContentType("text/html;charset=utf-8");  
            response.getWriter().write(resultjson);  
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 微信java验证
	 * @param para
	 * @param request
	 * @param response
	 * @param file
	 * @return
	 */
	@RequestMapping("weixinJavaValidate")
	public void weixinJavaValidate(String para,HttpServletRequest request, HttpServletResponse response){
		Map<String,Object> rm = new HashMap<String,Object>();  //返回信息map
		try{
			// 微信加密签名  
	        String signature = request.getParameter("signature");  
	        // 时间戳  
	        String timestamp = request.getParameter("timestamp");  
	        // 随机数  
	        String nonce = request.getParameter("nonce");  
	        // 随机字符串  
	        String echostr = request.getParameter("echostr");  
	  
	        PrintWriter out = response.getWriter();  
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
	            out.print(echostr);  
	        }  
	        out.close();  
	        out = null;  
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
 	public static void main(String[] args) throws Exception {
// 		String aa="{\"special_num_price\":\"2000\",\"user_id\":\"51\",\"action\":\"appCemetery/querySpecialNumList\",\"cemetery_number\":\"17855776\",\"cemetery_name\":\"测试接口网上墓园\"}";
 		String aa="{\"cemetery_name\":\"考虑\", \"action\":\"appCemetery/createCemeteryfast\", \"user_id\":\"56711\"}";
 		Map<String,Object> map= new HashMap<String,Object>();
 		map.put("action", "appAncestralHall/queryTj");
// 		m.put("flag", "0");
// 		m.put("cemetery_type","0");//墓园类型  0.单人墓；1.双人墓
		map.put("ancestral_hall_obid","55e41446cf1a2816004c39ff");  //用户id
 		map.put("mongo_id", "55e41446cf1a2816004c3a00");
		map.put("user_id_mongo", "55c0362ccf1a281288b59f2a");
		map.put("genealogy_name", "王77");
		map.put("genealogy_die", 0);
		map.put("genealogy_sex", "男");
		map.put("genealogy_seniority_current", 5);
//		map.put("ancestral_hall_province_code", 1);
//		map.put("ancestral_hall_city_code", 1);
//		map.put("ancestral_hall_country", "中国");
//		map.put("ancestral_hall_province", "黑龙江");
//		map.put("ancestral_hall_city", "哈尔滨");
		map.put("genealogy_obid_mongo", "55e554da068dfb19ecd9aff7");
		map.put("special_day", 26);
// 		List list  = new ArrayList();
// 		list.add("1");
// 		list.add("2");
//		map.put("flag","0");
//		map.put("minValue","-1");
 		//{user_id_mongo=55c0362ccf1a281288b59f2a, action=appCemetery/applyForIndexShow, cemetery_id=13964765, user_id=56766, special_cemetery_show_time=1438642620, date=1}
//		map.put("apply_user_id", "13964765");
//		map.put("apply_user_name", "name1");
//		map.put("apply_info", "1");
		
//		m.put("cemetery_user_name","管理员");  //用户昵称
// 		m.put("cemetery_name","网上墓园"); //墓园名称
// 		map.put("be_apply_user_id","55c0362ccf1a281288b59f2a"); //墓园号
// 		map.put("be_apply_user_name","name2");  //墓园id  55c0366bcf1a281288b59f2b
//		map.put("cemetery_id_mongo","55c0366bcf1a281288b59f2b");                            //墓园名称
// 		map.put("article_name","追思留言");                               //文章名称
// 		map.put( "article_info_url","");                                 //文章内容URL地址
// 		map.put( "user_id","55530645993dbd7061de64eb");                                      //发文章的用户ObjectId
// 		map.put( "user_name","test");                                      //发文章的用户昵称
// 		map.put( "av_user_obj_id","123");                                      //发文章用户的leancloud id
// 		map.put( "article_state",1);                              //文章状态 1完全公开 2亲友可见 3完全保密
 		
 		
 		System.out.println(JackJson.fromObjectToJson(map));
 		System.out.println(AES.encrypt(JackJson.fromObjectToJson(map)));
 		
// 		System.out.println(AES.encrypt(aa));
// 		System.out.println(AES.decrypt("x5v9VuQb6C/2+ZCxajMWcgZIliys4W6e/9ASV4E+hkGu9So6QDUIjkYzdCT9vZF9EHlJu5H3/8m1d3GYrmtpZferhepF2Px0nj+hTwF08C8="));
	}
}
